 @include "lib.awk"
 @include "quartile.awk"
 @include "mwu.awk"
 BEGIN { OFS=FS="," }
 /#/   { next }
 /audiology/       { gsub(/[ \t]*/,"")
		 Source=$1
         Key=$2
		 for(I=3;I<NF;I++) Key= Key OFS $I
         Db[Source][Key][NR] = $NF
         Db["_"   ][Key][NR] = $NF
        }
 END   {Com="sort -t, -n -k 5"
        for(Source in Db)  {
			print "# " Source
			array(Median)
			for(Key in Db[Source]) {
					asort(Db[Source][Key],All)
					tmp=median(All) + rand()/10000
			       	Median[Key] = tmp
					Index[tmp] = Key
                    Output[Key]= quartile(All,"Prefix="Key) 
                    print  quartile(All,"Prefix="Key)  | Com
            }
			close(Com)
	        asort(Median,Sorted)
			N=a1b2c4d8(Sorted,Splits)
			Rank[1]=1
            if(N>0) {
				for(I=1;I<=Splits[1];I++) A[I]=value2median(Sorted[I])
            	for(I=1;I<=Splits[1];I++) Label[I] = Rank[1]
            }
            if(N>1) {
				for(J=I;J<=Splits[2];J++) B[J]=value2median(Sorted[J])
				Rank[2] = Rank[1] + mwu(A,B,0,criticalValue(95))
				for(J=I;J<=Splits[2];J++) Label[J]=Rank[2]
			}
            if(N>2) {
				for(K=J;K<=Splits[3];K++) C[K]=value2median(Sorted[K])
				Rank[3] = Rank[2] + mwu(B,C,0,criticalValue(95))
				for(K=J;K<=Splits[3];K++) Label[K]=Rank[3]
			}
            if(N>3) {
				for(L=K;L<=Splits[4];L++) D[L]=value2median(Sorted[L])
				Rank[4] = Rank[3] + mwu(C,D,0,criticalValue(95))
				for(L=K;L<=Splits[4];L++) Label[L] =Rank[4]
			}	
            for(I=1;I<=length(Sorted);I++)
				print Label[I] "," Output[Index[Sorted[I]]]
       }}

  function value2median(x) {
	return Median[Index[x]]
  } 
  function a1b2c4d8(l,splits,     max,a,b,c,d) {
       max= length(l) 
	   a = int(max/15)
       if (a<1) a = 1
	   #------------------
	   if (a>max) a=max;
       while (a <max && (l[a] < l[a+1] - 0.001)) a++;
	   splits[1]=a;
	   if (a==max) return 1
	   #------------------
	   b = a * 2
	   if (b > max) b=max
       while (b < max && (l[b] < l[b+1] - 0.001)) b++
	   splits[2]=b
	   if (b==max) return 2
	   #------------------
       c= b * 2
	   if (c > max) c=max
       while (c < max && (l[c] < l[c+1] - 0.001)) c++
	   splits[3]=c
	   if (c==max) return 3
	   #------------------
       splits[4]=max
       return 4
 }

